

import { Button, Checkbox, Form, Input } from 'antd';
import React from 'react';
import {Fragment} from "react"
import * as api from "@/api/users"
import "./index.css"
import useStorage from '@/hooks/useStorage';
import {useNavigate} from "react-router-dom"

//表单校验通过
const Login: React.FC = () => {
    // 使用自定义的本地存储
    let[,tokenMethod]=useStorage("qf-token");
    let[,userInfoMethod]=useStorage("userInfo");
    let[,permissionMethod]=useStorage("permission")
    let navigate=useNavigate()
    
  const onFinish = (values: any) => {
    console.log('Success:', values);
    // 校验通过发起请求，将token存到本地，跳转页面
    api.loginApi(values.username,values.password)
    .then((res:any)=>{
       console.log(res)
       if(res.data.state){
          // 1.存token
          tokenMethod.set(res.data.token)
          // 2.存用户信息
          userInfoMethod.set(res.data.userInfo)
          // 3.存按钮权限
          permissionMethod.set(res.data.permission)
          // 4.跳转页面
          navigate("/")
       }
    })

  };
// 表单校验不通过
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
    
  };

// 校验输入框

const validatPassword = (rules:any,value:string) => {
  if(!value){
    return Promise.reject("输入框不能为空")
  }
  // 如果密码长度小于3
  if(value.length<3){
    return Promise.reject("请正确输入密码")
  }else{
    return Promise.resolve()
  }
}


  return (
    <Fragment>
    <div className="loginForm">
    <Form
      name="basic"
      labelCol={{ span: 2 }}
      wrapperCol={{ span: 5 }}
      initialValues={{ remember: true }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item
        label="用户名："
        name="username"
        rules={[{ required: true, message: '请输入用户名' }]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="密码："
        name="password"
        rules={[{ required: true, message: '请输入密码',validator:validatPassword }]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 2, span: 5 }}>
        <Checkbox>七天免登录</Checkbox>
      </Form.Item>

      <Form.Item wrapperCol={{ offset: 2, span: 5 }}>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
    </div>
    </Fragment>
  );
};

export default Login;

